package com.juzipi.demo.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.juzipi.demo.mapper.RoleMapper;
import com.juzipi.demo.mapper.UsersMapper;
import com.juzipi.demo.mapper.UserRoleMapper;
import com.juzipi.demo.pojo.Role;
import com.juzipi.demo.pojo.Users;
import com.juzipi.demo.pojo.UserRole;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private RoleMapper roleMapper;


    //通过用户名加载用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if (StringUtils.isBlank(username)){
            throw new RuntimeException("用户名为空");
        }
        //不为空根据用户名获取用户信息
        Users users = usersMapper.selectOne(new QueryWrapper<Users>().lambda().eq(Users::getUsername, username));
        if (users == null){
            throw new UsernameNotFoundException(String.format("%s用户不存在",username));
        }
        //存在就
        ArrayList<GrantedAuthority> authorities = new ArrayList<>();
        //根据用户id查询出用户的中间表中的 role id集合
        List<UserRole> userRoles = userRoleMapper.selectList(new QueryWrapper<UserRole>().lambda().eq(UserRole::getUserId, users.getId()));
        if (userRoles != null && !userRoles.isEmpty()){
            //根据中间表上面查询到的数据 把用户的roleId存到一个集合里
            List<Long> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
            //然后再查询出所有的角色
            List<Role> roles = roleMapper.selectList(new QueryWrapper<Role>().lambda().in(Role::getId, roleIds));
            roles.forEach(code->{
                //把角色信息传进去
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(code.getRoleCode());
                authorities.add(authority);
            });

        }
        //根据用户获取角色  根据登录的用户获取权限/角色集合
        return new User(users.getUsername(), users.getPassword(), authorities);
    }
}
